const db = require('../config/db')
const categoryDetailModel = '../schema/category_detail'
const categoryModel = '../schema/category'

const Mall = db.MallSequelize
const category = Mall.import(categoryModel)
const category_detail = Mall.import(categoryDetailModel)
category.hasMany(category_detail)
category_detail.belongsTo(category)
// 获取商品类别
const getCategorys = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await category.findAndCountAll(
    {
      // include: [category_detail],
      offset: parseInt(page*10)*parseInt(limit/10),
      limit: limit,
      order: [['created_at', 'desc']],
      where: {
        status: 1
      }
    }
  )
  return result
}
// 获取商品类别
const getCategory = async () => {
  const result = await category.findAll(
    {
      include: [category_detail],
      where: {
        status: 1
      }
    }
  )
  return result
}
// 添加商品类别
const addCategory = async (data) => {
  await category.create(
    {
      name: data.name,
      status: 1
    }
  )
  return true
}
// 根据id获取商品类别
const getCategoryById = async (id) => {
  const result = await category.findOne({
    where: {
      id: id
    }
  })
  return result
}
// 根据id修改商品类别
const updateCategoryById = async (id, data) => {
  await category.update(
    {
      name: data.name
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
// 根据搜索关键字获取商品类别
const getCategoryByKeyWords = async (keywords) => {
  if(keywords.id) {
    const result = await category.findAll(
      { 
        where: {
          id: Number(keywords.id)
        } 
      },
    )
    return result
  }else if(keywords.name) {
    const result = await category.findAll(
      { 
        where: {
          name: keywords.name
        } 
      },
    )
    return result
  }
}
// 删除商品类别
const deleteCategory = async (id) =>{
  await category.update(
    {
      status: 0
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
module.exports = {
  getCategorys,
  getCategory,
  addCategory,
  getCategoryById,
  updateCategoryById,
  getCategoryByKeyWords,
  deleteCategory
}